package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.util.Consts;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by 甘静斌 on 2020-08-07 20:19
 */
@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

    @Autowired
    private StringRedisTemplate template;

    @Override
    public void setVerifyCode(String phone, String code) {

        //key的见名知意,使用自己写的枚举类调用join方法来拼接key
        String key = RedisKeys.VERIFY_CODE.join(phone);

        template.opsForValue().set(key,code , Consts.VERIFY_CODE_VAI_TIME*60L ,TimeUnit.SECONDS );
    }

    @Override
    public String getVerifyCode(String phone) {

        String key = RedisKeys.VERIFY_CODE.join(phone);
        String code = template.opsForValue().get(key);
        return code;
    }

    @Override
    public String getToken(UserInfo user) {

        //通过uuid方式创建token令牌
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        //以token作为key,用户对象user作为value缓存到redis数据库中,并设置token的有效时间为30分钟

        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        String value = JSON.toJSONString(user);

        template.opsForValue().set(key,value , RedisKeys.USER_LOGIN_TOKEN.getTime(),TimeUnit.SECONDS );

        return token;
    }

    @Override
    public UserInfo getUserByToken(String token) {
        
        //判断user对象是否为null,决定当前是否已经登陆
        //判断token是否存在
        if (!StringUtils.hasLength(token)){
            return null;
        }
        //拼接token
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);
        //查redis中的token是否还存在,存在就拿出来
        if (template.hasKey(key)){
            //从redis中获取的是一个字符串类型
            String userStr = template.opsForValue().get(key);
            //返回json格式数据回浏览器
            UserInfo info = JSON.parseObject(userStr, UserInfo.class);

            //重置token的有效时间
            template.expire(key,Consts.USER_INFO_TOKEN_VAI_TIME*60L ,TimeUnit.SECONDS );
            return info;
        }
        return null;
    }

}
